<template>
  <el-dialog
    :title="`${teacherName} - 班级管理`"
    v-model="dialogVisible"
    width="800px"
  >
    <el-transfer
      v-model="selectedClasses"
      :data="allClasses"
      :titles="['未分配班级', '已分配班级']"
      :props="{
        key: 'id',
        label: item => item.name  // 只显示班级名称
      }"
      filterable
    >
      <!-- 自定义格式显示 -->
      <template #default="{ option }">
        {{ option.name }} ({{ option.id }})
      </template>
    </el-transfer>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { classService } from '../../services/class'
import { teacherService } from '../../services/teacher'
import { showSuccess, showError } from '../../utils/message'

const dialogVisible = ref(false)
const loading = ref(false)
const teacherName = ref('')
const teacherId = ref('')

const allClasses = ref([])
const selectedClasses = ref([])

const loadClasses = async () => {
  try {
    loading.value = true
    // 获取所有班级
    const { data } = await classService.getAllClasses()
    allClasses.value = data
  } catch (error) {
    showError('加载班级列表失败')
    console.error(error)
  }
}

const loadTeacherClasses = async () => {
  try {
    // 获取教师已分配的班级
    const classIds = await teacherService.getTeacherClasses(teacherId.value)
    selectedClasses.value = classIds
  } catch (error) {
    showError('加载教师班级失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const open = async (teacher) => {
  teacherId.value = teacher.id
  teacherName.value = teacher.name
  dialogVisible.value = true
  
  await loadClasses()
  await loadTeacherClasses()
}

const handleConfirm = async () => {
  try {
    loading.value = true
    await teacherService.assignClasses(teacherId.value, selectedClasses.value)
    showSuccess('保存成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    showError(error?.message || '保存失败')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
}

const emit = defineEmits(['success'])

defineExpose({
  open
})
</script>

<style scoped>
:deep(.el-transfer) {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}
</style>
